﻿/*
 * Copyright (c) 2010 Subodh.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 * 
 * 
DISCLAIMER: ilangl.Customer.DNN template is not affiliated nor endorsed by DNN Corp. 
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.UI;
using Telerik.Web.UI;
using DataCache = DotNetNuke.Common.Utilities.DataCache;
using Globals = DotNetNuke.Common.Globals;
using iLangl.Customer.DNN.Components;
using DotNetNuke.Entities.Modules.Actions;



namespace iLangl.Customer.DNN
{
	public partial class ProjectEdit : DnnModuleBase
	{
		#region Properties
		protected List<TabInfo> Tabs
		{
			get
			{
				return TabController.GetPortalTabs(PortalId, Null.NullInteger, false, true, false, true);
			}
		}

		private string SelectedNode
		{
			get
			{
				return (string)ViewState["SelectedNode"];
			}
			set
			{
				ViewState["SelectedNode"] = value;
			}
		}

		#endregion

		#region Content TreeView Event Handler

		void ctlPages_NodeExpand(object sender, RadTreeNodeEventArgs e)
		{
			AddChildnodes(e.Node);
		}
		#endregion

		#region Content TreeView Functionality
		private void AddAttributes(ref RadTreeNode node, TabInfo tab)
		{

		}
		private void BindTree()
		{
			ctlPages.Nodes.Clear();

			var rootNode = new RadTreeNode();
			var strParent = "-1";

			if (Settings["ParentPageFilter"] != null)
			{
				strParent = Convert.ToString(Settings["ParentPageFilter"]);
			}

			if (strParent == "-1")
			{
				rootNode.Text = PortalSettings.PortalName;
				rootNode.ImageUrl = GetIcon(IconManager.IconPortal);
				rootNode.Value = Null.NullInteger.ToString();
				rootNode.Expanded = true;
				rootNode.AllowEdit = false;
				rootNode.EnableContextMenu = true;
				rootNode.Attributes.Add("isPortalRoot", "True");
				AddAttributes(ref rootNode, null);
			}
			else
			{
				var tabController = new TabController();
				var parent = tabController.GetTab(Convert.ToInt32(strParent), -1, false);
				if (parent != null)
				{
					rootNode.Text = parent.TabName;
					rootNode.ImageUrl = GetIcon(IconManager.IconPortal);
					rootNode.Value = parent.TabID.ToString();
					rootNode.Expanded = true;
					rootNode.EnableContextMenu = true;
					rootNode.PostBack = false;
				}
			}


			foreach (var tab in Tabs)
			{
				if (TabPermissionController.CanViewPage(tab))
				{
					if (strParent != "-1")
					{
						if (tab.ParentId == Convert.ToInt32(strParent))
						{
							var node = new RadTreeNode { Text = string.Format("{0} {1}", tab.TabName, GetNodeStatusIcon(tab)), Value = tab.TabID.ToString(), AllowEdit = true, ImageUrl = GetNodeIcon(tab) };
							AddAttributes(ref node, tab);

							AddChildnodes(node);

							AddModules(node, tab);

							rootNode.Nodes.Add(node);
						}
					}
					else
					{
						if (tab.Level == 0)
						{
							var node = new RadTreeNode { Text = string.Format("{0} {1}", tab.TabName, GetNodeStatusIcon(tab)), Value = tab.TabID.ToString(), AllowEdit = true, ImageUrl = GetNodeIcon(tab) };
							AddAttributes(ref node, tab);

							AddChildnodes(node);

							AddModules(node, tab);

							rootNode.Nodes.Add(node);
						}
					}
				}
			}

			ctlPages.Nodes.Add(rootNode);
		}


		private void AddChildnodes(RadTreeNode parentNode)
		{
			parentNode.Nodes.Clear();


			var parentId = int.Parse(parentNode.Value);

			foreach (var objTab in Tabs)
			{
				if (objTab.ParentId == parentId)
				{
					var node = new RadTreeNode { Text = string.Format("{0} {1}", objTab.TabName, GetNodeStatusIcon(objTab)), Value = objTab.TabID.ToString(), AllowEdit = true, ImageUrl = GetNodeIcon(objTab) };

					AddChildnodes(node);
					parentNode.Nodes.Add(node);
				}
			}
		}

		private void AddModules(RadTreeNode parentnode, TabInfo tab)
		{
			var parentId = int.Parse(parentnode.Value);

			List<ModuleInfo> modules = GetChildModules(parentId, tab.CultureCode);
			foreach (ModuleInfo mi in modules)
			{

				var node = new RadTreeNode
				{
					Text = string.Format("{0}", mi.DesktopModule.ModuleName),
					Value = mi.ModuleID.ToString(),
					AllowEdit = true,
					ImageUrl = GetIcon(IconManager.ModuleIcon)
				};

				parentnode.Nodes.Add(node);
			}
		}

		#endregion

		#region Page Handler
		protected override void Page_Init(object sender, EventArgs e)
		{
		}

		protected override void OnInit(EventArgs e)
		{
			ctlPages.NodeExpand += new RadTreeViewEventHandler(ctlPages_NodeExpand);
		}

		protected override void OnLoad(EventArgs e)
		{
			try
			{
				CheckSecurity();

				if (Page.IsPostBack == false)
				{
					BindTree();
				}
			}
			catch (Exception exc) //Module failed to load
			{
				Exceptions.ProcessModuleLoadException(this, exc);
			}
		}


		private void CheckSecurity()
		{
			if ((!(TabPermissionController.HasTabPermission("CONTENT"))) && !(ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, "CONTENT, EDIT")))
			{
				Response.Redirect(Globals.NavigateURL("Access Denied"), true);
			}
		}



		protected void Page_Load(object sender, EventArgs e)
		{

		}
		#endregion

		public override ModuleActionCollection ModuleActions
		{
			get
			{
				MyActions.Add(this.GetNextActionID(), "Edit this Control", ModuleActionType.ModuleSettings, "", "", this.EditUrl(), false, SecurityAccessLevel.Admin, true, false);
				MyActions.Add(this.GetNextActionID(), "View Projects", ModuleActionType.ModuleSettings, "", "", this.EditUrl(), false, SecurityAccessLevel.Admin, true, false);

				return MyActions;
			}
		}


		#region Icons

		private string GetNodeStatusIcon(TabInfo tab)
		{
			if (tab.DisableLink)
			{
				return "<img src=\"" + GetIcon(IconManager.IconPageDisabled) + "\" class=\"statusicon\" />";
			}

			if (tab.IsVisible == false)
			{
				return "<img src=\"" + GetIcon(IconManager.IconPageHidden) + "\" class=\"statusicon\" />";
			}

			return "";
		}


		private string GetNodeIcon(TabInfo tab)
		{
			if (PortalSettings.HomeTabId == tab.TabID)
			{
				return GetIcon(IconManager.IconHome);
			}

			if (IsSecuredTab(tab))
			{
				if (IsAdminTab(tab))
				{
					return GetIcon(IconManager.AdminOnlyIcon);
				}

				if (IsRegisteredUserTab(tab))
				{
					return GetIcon(IconManager.RegisteredUsersIcon);
				}

				return GetIcon(IconManager.SecuredIcon);
			}

			return GetIcon(IconManager.AllUsersIcon);
		}



		#endregion

		#region Helper Methods
		private static bool IsSecuredTab(TabInfo tab)
		{
			var perms = tab.TabPermissions;
			return perms.Cast<TabPermissionInfo>().All(perm => perm.RoleName != "All Users" || !perm.AllowAccess);
		}

		private bool IsRegisteredUserTab(TabInfo tab)
		{
			var perms = tab.TabPermissions;
			return perms.Cast<TabPermissionInfo>().Any(perm => perm.RoleName == PortalSettings.RegisteredRoleName && perm.AllowAccess);
		}

		private bool IsAdminTab(TabInfo tab)
		{
			var perms = tab.TabPermissions;
			return perms.Cast<TabPermissionInfo>().All(perm => perm.RoleName == PortalSettings.AdministratorRoleName || !perm.AllowAccess);
		}


		#endregion

		#region Modules Section
		private List<ModuleInfo> GetChildModules(int tabId, string cultureCode)
		{
			var modules = new List<ModuleInfo>();
			var tabCtrl = new TabController();
			Locale locale = LocaleController.Instance.GetLocale(cultureCode);
			if (locale != null)
			{
				modules = (from kvp in tabCtrl.GetTabByCulture(tabId, PortalSettings.PortalId, locale).ChildModules where !kvp.Value.IsDeleted select kvp.Value).ToList();
			}
			return modules;
		}

		#endregion
	}
}
